﻿using System;
using System.Net;
using System.Web;
using System.Web.Mvc;
using VietThinks.Web.Mvc;
using FutureVision.Infrastructure;
using VietThinks.Website.Controllers;      

namespace VietThinks.Website.ActionFilter
{
    public class HandleErrorExAspect : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                filterContext.ExceptionHandled = true;

                var signaledError = filterContext.Exception is HttpException
                    ? filterContext.Exception
                    : new HttpException((int)HttpStatusCode.InternalServerError, filterContext.Exception.Message, filterContext.Exception);

                Elmah.ErrorSignal.FromCurrentContext().Raise(signaledError);

                if (!filterContext.HttpContext.IsCustomErrorEnabled)
                {
                    filterContext.Controller.TempData["Description"] = filterContext.Exception.Message;
                    filterContext.Controller.TempData["Source"] = filterContext.Exception.Source;
                    filterContext.Controller.TempData["StackTrace"] = filterContext.Exception.StackTrace;
                }

                ((Controller)filterContext.Controller).RedirectToAction<ErrorController>(c => c.Show())
                    .ExecuteResult(filterContext.Controller.ControllerContext);
            }
        }
    }
}
